package com.poll.controller;

import com.poll.entity.User;
import com.poll.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by XYZ on 2018/1/8.
 */
@Controller
@RequestMapping("/user")
@SessionAttributes("user")
public class LoginController {
    @Autowired
    UserService userService;
    @RequestMapping("/prelogin")
    public String preLogin(String info,Model model, @CookieValue(value = "user", required = false) String userInfo) {

        if (userInfo != null) {
            String[] infoArr = userInfo.split(":");
            model.addAttribute("username", infoArr[0]);
            model.addAttribute("password", infoArr[1]);
        }
        model.addAttribute("info", info);
        return "login.jsp";
    }
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String userLogin(HttpServletRequest request, HttpServletResponse response, Model model, String username, String password){
        User user = userService.login(username, password);
        if (user != null) {

            model.addAttribute("user", user);
            //登陆成功,则跳转到下一个页面
            return "/WEB-INF/index.jsp";
        } else{

            model.addAttribute("info", 1);
            return "login.jsp";
        }
    }
}
